package com.yc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.Result;
import com.yc.entities.BloodSugarBed;
import com.yc.entities.BloodSugarGluce;
import com.yc.entities.BloodSugarGluceProgram;
import com.yc.entities.BloodSugarPatientInfo;
import com.yc.entities.custom.AppHomePageUserBean;
import com.yc.entities.custom.GluceDataTable;
import com.yc.mapper.BloodSugarGluceMapper;
import com.yc.service.BloodSugarGluceProgramService;
import com.yc.service.BloodSugarGluceService;
import com.yc.service.BloodSugarPatientInfoService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.IntStream;

/**
 * <p>
 * 血糖测量数据 服务实现类
 * </p>
 *
 * @author kuakha
 * @since 2021-04-07
 */
@Service
public class BloodSugarGluceServiceImpl extends ServiceImpl<BloodSugarGluceMapper, BloodSugarGluce> implements BloodSugarGluceService {

    @Autowired
    private BloodSugarGluceProgramService bloodSugarGluceProgramService;

    @Autowired
    private BloodSugarPatientInfoService bloodSugarPatientInfoService;

    @Override
    public Result getGluceDataByType(String userId, String attr) {
        if (StringUtils.isEmpty(userId)) {
            return Result.error().code(301).message("用户id不能为空");
        }
        Map<String, Object> map = new HashedMap();
        List<BigDecimal> maxList = new ArrayList<>();
        List<Double> average = new ArrayList<>();
        List<BloodSugarGluce> gluceDataByType = this.baseMapper.getGluceDataByType(userId, attr);
        System.out.println("+++++++++++++++++++++++++++++"+gluceDataByType);
        if (CollectionUtil.isNotEmpty(gluceDataByType)) {
            map.put("sevenData", gluceDataByType);
            gluceDataByType.forEach(value -> average.add(value.getGluceValue().doubleValue()));
            //最大最小
            gluceDataByType.forEach(value -> maxList.add(value.getGluceValue()));
            BigDecimal max = Collections.max(maxList);
            maxList.clear();
            gluceDataByType.forEach(value -> maxList.add(value.getGluceValue()));
            BigDecimal min = Collections.min(maxList);

            double averageData = average.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
            BigDecimal a = new BigDecimal(averageData);
            BigDecimal averageNum = a.setScale(1, RoundingMode.HALF_UP);
            map.put("minData", min);
            map.put("maxData", max);
            map.put("averageData", averageNum);
        }
        return Result.ok().data(map);
    }

    @Override
    public Result getGluceDataByDate(String userId, String dateType) {
        if (StringUtils.isEmpty(userId)) {
            return Result.error().code(301).message("用户id不能为空");
        }
        List<GluceDataTable> date = new ArrayList<>();
        List<GluceDataTable> gluceDataByDate = this.baseMapper.getGluceDataByDate(userId, dateType);
        System.out.println(gluceDataByDate.size());
        if (CollectionUtil.isNotEmpty(gluceDataByDate)) {
            gluceDataByDate.forEach(gluceDataTable -> {
                List<BloodSugarGluce> sugarGluces = new ArrayList<>();
                IntStream.rangeClosed(0, 9).forEach(attr -> {
                    BloodSugarGluce b = new BloodSugarGluce();
                    b.setGluceAttr(attr);
                    b.setGluceValue(new BigDecimal(0.0));
                    sugarGluces.add(b);
                });
                GluceDataTable gluceData = new GluceDataTable();
                String gluceExamtime = gluceDataTable.getGluceExamtime();
                gluceData.setGluceExamtime(gluceExamtime);
                List<BloodSugarGluce> bloodSugarGluces = gluceDataTable.getBloodSugarGluces();
                sugarGluces.forEach(s -> {
                    bloodSugarGluces.forEach(n -> {
                        if (s.getGluceAttr().equals(n.getGluceAttr())) {
                            s.setGluceValue(n.getGluceValue());
                            s.setGluceState(n.getGluceState());
                        }
                    });
                });
                gluceData.setBloodSugarGluces(sugarGluces);
                date.add(gluceData);
            });
            System.out.println(date.size());
            return Result.ok().code(200).data(date);
        } else {
            return Result.ok().code(300).message("暂无数据");
        }
    }

    @Override
    public int abnormalDataCount(String doctorId, String departmentId) {
        return this.baseMapper.abnormalDataCount(doctorId, departmentId);
    }

    @Override
    public List<AppHomePageUserBean> getAbnormalDataByUser(BloodSugarPatientInfo bloodSugarPatientInfo) {
        return this.baseMapper.getAbnormalDataByUser(bloodSugarPatientInfo);
    }

    @Override
    public List<BloodSugarGluce> getGluceDataByAttrAndNow(String attr, String userId) {
        return this.baseMapper.getGluceDataByAttrAndNow(attr, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertSugarDataByUser(String userId, String attr, String sugarValue, String examTime) {
        if (StringUtils.isEmpty(userId)) {
            return Result.ok().code(301).message("用户Id不能为空");
        }
        if (StringUtils.isEmpty(attr)) {
            return Result.ok().code(302).message("血糖测量时间段为空");
        }
        if (StringUtils.isEmpty(sugarValue)) {
            return Result.ok().code(303).message("血糖测量数据不能为空");
        }
        if("10".equals(attr)||"11".equals(attr)){
            attr = "8";
        }else if ("12".equals(attr)){
            attr = "7";
        }
        QueryWrapper<BloodSugarGluceProgram> query = Wrappers.query();
        query.eq("program_gl_attr", attr);
        query.eq("program_gl_userid", userId);
        BloodSugarGluceProgram sugarGluceProgram = bloodSugarGluceProgramService.getOne(query);
        QueryWrapper<BloodSugarPatientInfo> queryUser = Wrappers.query();
        queryUser.eq("id", userId);
        BloodSugarPatientInfo one = bloodSugarPatientInfoService.getOne(queryUser);
        double velue = Double.parseDouble(sugarValue);
        String gluce_state = "0";
        if (sugarGluceProgram.getProgramGlUpvalue() > velue && sugarGluceProgram.getProgramGlDownvalue() < velue) {
            gluce_state = "0";
        } else if (sugarGluceProgram.getProgramGlUpvalue() < velue) {
            gluce_state = "1";
        } else if (sugarGluceProgram.getProgramGlDownvalue() > velue) {
            gluce_state = "2";
        }

        BloodSugarGluce sugarGluce = new BloodSugarGluce();

        sugarGluce.setGluceUserid(Integer.parseInt(userId));
        sugarGluce.setGluceAddtime(new Date());
        BigDecimal bigDecimal = new BigDecimal(velue);
        sugarGluce.setGluceAttr(Integer.parseInt(attr));
        bigDecimal.setScale(1, RoundingMode.HALF_UP);
        sugarGluce.setGluceValue(bigDecimal);
        sugarGluce.setGluceState(Integer.parseInt(gluce_state));
        sugarGluce.setGluceDepartment(one.getDepartmentId());
        sugarGluce.setGluceDeanid(one.getDeanId());
        if (StringUtils.isNotEmpty(examTime)){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date parse = simpleDateFormat.parse(examTime);
                sugarGluce.setGluceExamtime(parse);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else{
            sugarGluce.setGluceExamtime(new Date());
        }
        int insert = this.baseMapper.insert(sugarGluce);
        if (insert > 0) {
            return Result.ok().message("数据添加成功");
        } else {
            return Result.error().message("数据添加失败");
        }
    }
}
